<template>
  <div :class="{'mui-refresh-container': true,'navigationbar': navigationbar,'tabbar': tabbar}">
    <div class="mui-scroll">
      <slot></slot>
    </div>
  </div>
</template>
<script>
export default {
  name: "mui-refresh",
  data() {
    return {
      dataArray: [], //数据源
      startPage: 0, //开始页码
      currentPage: 0 //当前页码
    };
  },
  props: {
    // ui相关
    navigationbar: {
      //是否有导航
      type: Boolean,
      default: true
    },
    tabbar: Boolean, //是否有tabbar
    // 接口相关
    scheme: String, //接口前缀
    params: Object, //参数
    isLogin: Boolean, //是否需要登录
    name: {
      //接口名称
      type: String,
      default: "网络请求"
    },
    callback: Function //数据源回调
  },
  methods: {
    //   初始化mui
    initMui() {
      this.$.mui.init({
        pullRefresh: {
          container: ".mui-refresh-container",
          down: {
            style: "circle", //必选，下拉刷新样式，目前支持原生5+ ‘circle’ 样式
            auto: true, //可选,默认false.首次加载自动下拉刷新一次
            callback: () => {
              this.requestData(this.startPage);
            }
          },
          up: {
            callback: () => {
              this.requestData(this.currentPage + 1);
            }
          }
        }
      });
    },
    // 请求数据
    requestData(page) {
      var data = this.params || {};
      data.page = page;
      data.count = 10;
      this.$.http
        .post(this.scheme, data, this.name, this.isLogin)
        .then(response => {
          response = response.data;
          if (page == this.startPage) {
            this.dataArray = response;
          } else {
            this.dataArray = this.dataArray.concat(response);
          }
          this.currentPage = page;
          if (this.callback) this.callback(this.dataArray);
          // 结束刷新
          this.endRefresh(page);
        })
        .catch(response => {
          // 结束刷新
          this.endRefresh(page);
        });
    },
    // 结束刷新
    endRefresh(page) {
      if (page == this.startPage) {
        this.$.mui(".mui-refresh-container")
          .pullRefresh()
          .endPulldownToRefresh();
      } else {
        this.$.mui(".mui-refresh-container")
          .pullRefresh()
          .endPullupToRefresh();
      }
    },
    // 重置mui
    resetMui() {
      // 防止切换路由的时候mui初始化刷新失败
      for (var i = 0; i < this.$.mui.hooks.inits.length; i++) {
        var item = this.$.mui.hooks.inits[i];
        if (item.name == "pullrefresh") {
          item.repeat = true;
        }
      }
    }
  },
  mounted() {
    // 重置mui
    this.resetMui();
    // 初始化mui
    this.initMui();
  }
};
</script>
<style scoped>
.mui-refresh-container {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  overflow: hidden;
}
.mui-refresh-container.navigationbar {
  top: 1.17rem;
}
.mui-refresh-container.tabbar {
  bottom: 1.31rem;
}
</style>